package controller;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.User;

import core.CurrentUser;
import core.PgSQL;
import core.View;

public class UserList extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static PgSQL db = PgSQL.getInstance();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		CurrentUser user = new CurrentUser(request);
		if(!user.getGroup().isAdministrator()){
			View.showMessage(request, response, "Permission denied.", null);
			return;
		}
		
		ResultSet rs = db.query("SELECT u.*,g.groupname FROM qz_user u LEFT JOIN qz_usergroup g ON g.groupid=u.groupid ORDER BY u.uid");
		try{
			LinkedList<User> userlist = new LinkedList<User>();
			LinkedList<String> groupname = new LinkedList<String>();
			while(rs.next()){
				User u = User.fromDatabase(rs);
				groupname.add(rs.getString(6));
				userlist.add(u);
			}
			request.setAttribute("userlist[]", userlist.toArray(new User[0]));
			request.setAttribute("groupname[]", groupname.toArray(new String[0]));
			View.show(request, response, "user_list");
			
		}catch(SQLException e){
			e.printStackTrace();
			View.alertSystemCrash(request, response);
		}
	}

}
